﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace Microsoft.OpportunityPortal
{
    public class CaseStudy
    {
        /// <summary>
        /// Usage operation for lists: Global Case Study and Opportunity Request
        /// </summary>
        public enum UsageOperation
        {
            Increment,
            Decrement
        }

        public static bool ProcessCaseStudyEvent(SPItemEventProperties properties)
        {
            bool result = false;

            try
            {
                // Algo:
                // 1. Get Root Site URL
                // 2. Retrieve Case Study Reference 
                // 3. Search for the "Case Study" with the referred Case Study
                // 4. Update Case Study reference count
                // Scenarios: 1. Add reference 2. Delete Reference 3. Modify reference: click update button without making any changes. 4. modify reference:
                // Change the case study and click on update button.
            
                // 1. Get Root Site URL 
                string rootSiteURL = properties.Web.Site.Url;

                // Check if the list exists or not
                SPList globalCaseStudyList = properties.Web.ParentWeb.Lists["Global Case Study"];

                // 2. Retrieve Case Study Reference lookup field
                if (true == properties.ListItem.Fields.ContainsField("Case Study Reference"))
                {
                    if (properties.ListItem["Case Study Reference"] != null)
                    {
                        // Parse lookup value
                        string caseStudyRef = properties.ListItem["Case Study Reference"].ToString();
                        int itemId = SPOperations.ReturnLookupID(caseStudyRef);

                        string csrBkup = string.Empty;

                        if (properties.ListItem["CSRBkup"] != null)
                        {
                            csrBkup = properties.ListItem["CSRBkup"].ToString();
                        }

                        // Check if the event is "deleting" then decrement the count
                        if (properties.EventType == SPEventReceiverType.ItemDeleting)
                        {
                            UpdateUsageCountInGlobalCaseStudyList(properties.Web.ParentWeb.Url, "Global Case Study", "Usage", itemId, UsageOperation.Decrement);
                        }
                        else if (itemId != 0)
                        {
                            // Check if the csrbkup field contains value. If it doesn't that means it's a new entry added. If it contains then check the event
                            // If value matches, then do nothing else increment the usage count.
                            if (string.IsNullOrEmpty(csrBkup) == true)
                            {
                                // Value not updated
                                UpdateUsageCountInGlobalCaseStudyList(properties.Web.ParentWeb.Url, "Global Case Study", "Usage", itemId, UsageOperation.Increment);

                                // Update bkup field value
                                properties.ListItem["CSRBkup"] = properties.ListItem["Case Study Reference"];
                                properties.ListItem.Update();
                            }
                            else if (string.Compare(caseStudyRef, csrBkup, true) != 0)
                            {
                                // Decrement the count for the old referenced Case Study
                                UpdateUsageCountInGlobalCaseStudyList(properties.Web.ParentWeb.Url, "Global Case Study", "Usage", itemId, UsageOperation.Decrement);

                                itemId = SPOperations.ReturnLookupID(csrBkup);
                                // Increment the count for the newly referenced Case Study
                                UpdateUsageCountInGlobalCaseStudyList(properties.Web.ParentWeb.Url, "Global Case Study", "Usage", itemId, UsageOperation.Increment);

                                // Update bkup field value
                                properties.ListItem["CSRBkup"] = properties.ListItem["Case Study Reference"];
                                properties.ListItem.Update();
                            }
                        }
                    }
                }
            }
            catch (Exception expn)
            {
                Dictionary<string, string> errorLog = new Dictionary<string, string>();
                errorLog.Add("Title", "Error_" + DateTime.Now.ToLongTimeString());
                errorLog.Add("Description", expn.Message);
                errorLog.Add("EventType", "Error");

                SPOperations.AddUpdateListItem(properties.WebUrl, "Logger", errorLog, SPEventType.Add);
                return false;
            }

            return result;
        }       

        private static void UpdateUsageCountInGlobalCaseStudyList(string siteURL, string listName, string columnName, int itemID, UsageOperation usageOp)
        {
            using (SPSite site = new SPSite(siteURL))
            {
                using (SPWeb web = site.OpenWeb())
                {
                    SPList list = web.Lists[listName];
                    SPListItem item = list.GetItemById(itemID);
                    int count = 0;

                    if (item[columnName] != null)
                    {
                        int.TryParse(item[columnName].ToString(), out count);
                    }

                    // Update the usage count
                    if (usageOp == UsageOperation.Increment)
                    {
                        item[columnName] = ++count;
                    }
                    else 
                    {
                        // Check if the count is not equal to ZERO
                        if (count > 0)
                        {
                            item[columnName] = --count;
                        }
                    }

                    item.Update();
                }

            }
        }
    }
}
